package com.ysfxt.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysfxt.constant.RedisConst;
import com.ysfxt.jwt.JwtHelper;
import com.ysfxt.model.SysTeacher;
import com.ysfxt.model.SysUser;
import com.ysfxt.result.Result;
import com.ysfxt.result.ResultCodeEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 盐酸氟西汀
 * @create 2024/1/25 16:18
 * @email 480738950@qq.com
 */
public class UserLoginInterceptor implements HandlerInterceptor {
    private RedisTemplate redisTemplate;
    public UserLoginInterceptor (RedisTemplate redisTemplate) {
        this.redisTemplate =redisTemplate;
    }
    
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        //判空
        if(!StringUtils.isEmpty(token)){
            //检查是否有效
            boolean expiration = JwtHelper.isExpiration(token);
            if(expiration){
                //无效在响应头中返回208状态json
                Result result=Result.build(null, ResultCodeEnum.LOGIN_AUTH);
                ObjectMapper objectMapper=new ObjectMapper();
                String json = objectMapper.writeValueAsString(result);
                response.getWriter().print(json);
                return false;
            }
            //获取userId
            Long userId = JwtHelper.getUserId(token);
            String type =JwtHelper.getType(token);
            if(type.equals(RedisConst.USER_LOGIN_KEY_PREFIX)){
                //用户登录
                SysTeacher user = (SysTeacher) redisTemplate.opsForValue().get(RedisConst.USER_LOGIN_KEY_PREFIX + userId);
                if(user!=null){
                    AuthContextHolder.setTeacherId(user.getId());
                    AuthContextHolder.setTeacherLoginVo(user);
                }
            }else{
                //管理员登录
                SysUser sysUser = (SysUser) redisTemplate.opsForValue().get(RedisConst.ADMIN_LOGIN_KEY_PREFIX + userId);
                if(sysUser!=null){
                    AuthContextHolder.setAdminId(sysUser.getId());
                    AuthContextHolder.setAdminLoginVo(sysUser);
                }
            }
            return true;
        }else{
            //无效在响应头中返回208状态json
            Result result=Result.build(null, ResultCodeEnum.LOGIN_AUTH);
            ObjectMapper objectMapper=new ObjectMapper();
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().print(json);
            return false;
        }
    }
}